<template>
  <div>
    <el-form ref="form" :model="form" :rules="rules" label-width="100px">
      <el-form-item label="部门名称" prop="name">
        <el-input v-model="form.name" />
      </el-form-item>
      <el-form-item label="部门编码" prop="code">
        <el-input v-model="form.code" />
      </el-form-item>
      <el-form-item label="部门负责人" prop="manager">
        <el-select v-model="form.manager" placeholder="请选择部门负责人">
          <!-- 渲染数据 -->
          <el-option
            v-for="item in employeeList"
            :key="item.id"
            :label="item.username"
            :value="item.username"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="部门描述" prop="introduce">
        <el-input v-model="form.introduce" type="textarea" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="deptSubmit">确定</el-button>
        <el-button @click="cancel">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
// 引入 API接口
import { getEmployeeSimpleAPI, addDepartmentsAPI, getDepartmentAPI, editDepartmentsAPI } from '@/api/departments'
export default {
  name: 'DeptDialog',
  props: {
    origanList: {
      type: Array,
      required: true
    },
    parentId: {
      type: [String, Number],
      required: true
    },
    isEdit: {
      type: Boolean,
      required: true
    }
  },
  data() {
    // 自定义部门编码验证  部门编码不予许与整个部门的编码重复
    const validCode = (rule, value, callback) => {
      // 将部门编码拿出来，形成一个新的数组
      let existCodeList = this.origanList.map(item => item.code)
      // 判断 如果是编辑
      if (this.isEdit) {
        // 使用 filter 方法，将本项排除，再组成一个新的code数组
        existCodeList = this.origanList.filter(item => item.id !== this.parentId).map(item => item.code)
      }
      // ES6  新方法  includes  判断 填入的编码value 是否存在在整个部门编码中
      existCodeList.includes(value) ? callback(new Error(`部门编码 ${value} 已存在`)) : callback()
    }
    const validName = (rule, value, callback) => {
      // filter 将同级部门找到
      // map 将同级部门的部门名称找出来组成新的数组
      let existNameList = this.origanList.filter(item => item.pid === this.parentId).map(item => item.name)
      if (this.isEdit) {
        // 获取本身
        const obj = this.origanList.find(item => item.id === this.parentId)
        // console.log(obj)
        // 获取pid
        const pid = obj.pid
        // filter
        existNameList = this.origanList
          // 找到同级 同时把本身排除
          .filter(item => item.pid === pid && item.id !== this.parentId)
          // 将名字组成一个新数组
          .map(item => item.name)
      }
      // ES6  新方法  includes  判断 填入的编码value 是否存在在同级部门中
      existNameList.includes(value) ? callback(new Error(`部门名称 ${value} 在同级部门已存在`)) : callback()
    }
    return {
      form: {
        code: '',
        introduce: '',
        manager: '',
        name: ''
      },
      employeeList: [],
      rules: {
        name: [
          { required: true, message: '部门名称不能为空', trigger: 'blur' },
          { min: 1, max: 50, message: '部门名称要求1-50个字符', trigger: 'blur' },
          { validator: validName, trigger: 'blur' }
        ],
        code: [
          { required: true, message: '部门编码不能为空', trigger: 'blur' },
          { min: 1, max: 50, message: '部门编码要求1-50个字符', trigger: 'blur' },
          { validator: validCode, trigger: 'blur' }
        ],
        manager: [
          { required: true, message: '部门负责人不能为空', trigger: 'change' }
        ],
        introduce: [
          { required: true, message: '部门介绍不能为空', trigger: 'blur' },
          { min: 1, max: 300, message: '部门介绍要求1-300个字符', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    // 调用 获取员工列表 的方法
    this.getEmployeeSimple()
    if (this.isEdit) {
      this.getDepartment()
    }
  },
  methods: {
    // 数据回显
    async getDepartment() {
      const res = await getDepartmentAPI(this.parentId)
      this.form = res.data
    },
    // 获取员工列表
    async getEmployeeSimple() {
      const res = await getEmployeeSimpleAPI()
      this.employeeList = res.data
    },
    // 点击确定按钮，根据isEdit的值来判断是添加还是编辑
    deptSubmit() {
      this.$refs.form.validate(valid => {
        if (!valid) return
        this.isEdit ? this.editDepartment() : this.addDepartment()
      })
    },
    // 点击确定按钮 添加部门
    async addDepartment() {
      if (!this.isEdit) {
        const res = await addDepartmentsAPI({ ...this.form, pid: this.parentId })
        //   console.log(res)
        // 给用户提示
        this.$message.success(res.message)
        // 关闭弹框，刷新页面
        this.$emit('addDeptEvent')
        // 清空输入框内容
        this.form = {}
      }
    },
    // 点击确定按钮 编辑部门 更新部门信息
    async editDepartment() {
    //   console.log(this.form)

      const res = await editDepartmentsAPI(this.form)
      this.$message.success(res.message)
      // 关闭弹框，刷新页面
      this.$emit('editDeptEvent')
    },

    // 取消
    cancel() {
      // 关闭弹框
      this.$emit('closeEvent')
      // 清空输入框内容
      this.form = {}
    }
  }
}
</script>

<style >
.el-form {
  padding: 0 50px 0 20px;
}
.el-select {
  width: 100%;
}
</style>
